<template>
  <el-dialog v-loading="loading" :visible="visible"
             :append-to-body="true" :close-on-click-modal="false"
             title="编辑跟进记录"
             width="700px" class="no-padding-dialog"
             @close="handleCancel">
    <div class="mix-content">
      <div class="mix-content__body">
        <div class="mix-content-select">
          <el-select v-if="showContacts" v-model="selectContactsId"
                     clearable placeholder="选择联系人">
            <el-option v-for="item in contacts" :key="item.contactsId"
                       :label="item.name" :value="item.contactsId"/>
          </el-select>
          <el-select v-model="followType" clearable
                     placeholder="选择跟进方式">
            <el-option v-for="item in followTypes" :key="item.value"
                       :label="item.label"
                       :value="item.value"/>
          </el-select>
          <el-date-picker v-model="nextTime" :editable="false"
                          type="datetime"
                          placeholder="选择下次联系时间"
                          value-format="YYYY-MM-DD HH:mm:ss"/>
          <common-words @select="commonWordsSelect"/>
        </div>
        <div class="i-cont">
          <el-input ref="textarea"
                    v-model="content"
                    :autosize="autosize"
                    :maxlength="800"
                    type="textarea"
                    clearable
                    resize="none"
                    placeholder="请输入内容"
                    @focus="inputFocus"/>
        </div>
        <add-image-list v-if="imgFiles.length > 0" :data="imgFiles"
                        @delete="deleteImage"
                        @delete-all="deleteAllFile(2)"
                        @upload="uploadFile"/>
        <add-file-list v-if="files.length > 0" :data="files"
                       @delete="deleteFile"
                       @delete-all="deleteAllFile(1)"/>
        <add-relate-list v-if="business.length > 0" :data="business"
                         type="business"
                         @delete="deleteRelate"/>
      </div>

      <div class="bar-cont">
        <el-button link class="handle-button" icon="wk wk-picture"
                   @click="barClick('img')">图片
        </el-button>
        <el-button link class="handle-button" icon="wk wk-file"
                   @click="barClick('file')">附件
        </el-button>
        <el-popover v-if="showBusiness" v-model:visible="showBusinessPopover"
                    placement="bottom"
                    width="700"
                    popper-class="no-padding-popover"
                    trigger="click">
          <crm-relative ref="crmrelative" :show="showBusinessPopover"
                        :radio="false"
                        :action="businessAction"
                        :selected-data="{ 'business': business }"
                        crm-type="business"
                        @close="showBusinessPopover=false"
                        @changeCheckout="checkRelativeInfos"/>
          <template v-slot:reference>
            <el-button link icon="wk wk-associate"
                       class="handle-button" style="margin-left: 10px;"
                       @click="barClick('business')">关联商机
            </el-button>
          </template>

        </el-popover>
      </div>

      <!-- 附件 -->
      <input ref="fileInput" accept="*.*"
             type="file" class="file-input" multiple
             @change="uploadFile">
      <input ref="imgInput" accept="image/*"
             type="file" class="file-input" multiple
             @change="uploadFile">
    </div>
    <template v-slot:footer>
      <span class="dialog-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button v-debounce="handleConfirm" type="primary">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import {ref, watch, computed, getCurrentInstance} from "vue"

import {crmFileDeleteAPI, crmFileRemoveByBatchIdAPI} from '/src/api/common.js'
import {crmSettingRecordListAPI} from '/src/api/admin/crm.js'
import {crmActivityUpdateAPI} from '/src/api/crm/common.js'
import {crmCustomerQueryContactsAPI} from '/src/api/crm/customer.js'
import {objDeepCopy} from '/src/utils/index.js'


import CrmRelative from '/src/components/CreateCom/CrmRelative.vue'
import AddImageList from '/src/szcomponent/QuickAdd/AddImageList.vue'
import AddFileList from '/src/szcomponent/QuickAdd/AddFileList.vue'
import AddRelateList from '/src/szcomponent/QuickAdd/AddRelateList.vue'
import CommonWords from '/src/szcomponent/CommonWords/index.vue'

import {fileSize, getFileTypeIcon, getFileIconWithSuffix} from '/src/utils/index.js'
import crmTypeModel from '/src/views/crm/model/crmTypeModel.js'

const cxt = getCurrentInstance() //相当于Vue2中的this
const bus = cxt.appContext.config.globalProperties.$bus
const $wkUploadFile = cxt.appContext.config.globalProperties.$wkUploadFile

defineOptions({
  /** 跟进记录 下的 添加 有添加框的都需要*/
  name: 'LogEditDialog',
})

const props = defineProps({
  visible: {
    type: Boolean,
    required: true,
    default: false
  },
  data: Object
})

const emits = defineEmits(['focus', 'save', 'update:visible']);

const loading = ref(false)
const crmType = ref('')
/** 输入法 */
const content = ref('')
/** 图片信息 */
const imgFiles = ref([])
const businessAction = ref({}) // 关联商机注入的客户信息
/** 图片信息 */
const files = ref([])
/** 关联商机信息 */
const showBusinessPopover = ref(false)
const business = ref([])
/** 关联联系人信息 */
const contacts = ref([])
const selectContactsId = ref('')
const followTypes = ref([])
const followType = ref('')
// 下次联系时间
const nextTime = ref('')
/** 展示关联弹窗 */
const showRelativeType = ref('')
const batchId = ref('') // 批次ID


const autosize = computed(() => {
  return {minRows: 4, maxRows: 8}
})

const id = computed(() => {
  return props.data ? props.data.activityTypeId : ''
})

const showBusiness = computed(() => {
  return crmType.value == 'customer'
})

const showContacts = computed(() => {
  return showBusiness.value
})

watch(() => props.visible, (val) => {
      if (val) {
        const newCrmType = crmTypeModel.convertTypeToKey(props.data.activityType)
        if (crmType.value != newCrmType) {
          crmType.value = newCrmType
        }
        handleDetailInfo(objDeepCopy(props.data))
      }
    }, {
      immediate: true,
      deep: true
    }
)

watch(id, () => {
      businessAction.value = {type: 'condition', data: {moduleType: crmType.value, customerId: id.value}}
    }, {
      immediate: true
    }
)


/**
 * 操作详情数据
 */
const handleDetailInfo = (data) => {
  if (showContacts.value) {
    getContactsList()
  }

  if (followTypes.value.length == 0) {
    getLogTypeList()
  }
  content.value = data.content
  imgFiles.value = data.img || []
  const files = data.file || []
  files.value = files.map(item => {
    item.icon = getFileTypeIconLocal(item.name)
    return item
  })


  const businessList = data.businessList || []
  this.business = businessList.map(item => {
    return {
      businessName: item.name,
      businessId: item.id
    }
  })
  selectContactsId.value = data.contactsList && data.contactsList.length ? data.contactsList[0].id : ''
  followType.value = data.category
  nextTime.value = data.nextTime
  batchId.value = data.batchId
}

/**
 * 获取图标
 */
const getFileTypeIconLocal = (url) => {
  if (!url) return ''
  const temps = url ? url.split('.') : []
  let ext = ''
  if (temps.length > 0) {
    ext = temps[temps.length - 1]
  } else {
    ext = ''
  }

  return getFileIconWithSuffix(ext)
}

/**
 * 获取跟进类型详情
 */
const getLogTypeList = () => {
  crmSettingRecordListAPI().then(res => {
    followTypes.value = res.data.data.map(item => {
      return {
        value: item,
        label: item
      }
    })
  }).catch(() => {
  })
}

/**
 * 获取联系人
 */
const getContactsList = () => {
  crmCustomerQueryContactsAPI({
    customerId: this.id
  }).then(res => {
    contacts.value = res.data.data.list
  }).catch(() => {
  })
}

/**
 * 跟进类型初始值
 */
const getDefalutFollowType = () => {
  if (followTypes.value && followTypes.value.length > 0) {
    followType.value = followTypes.value[0].value
  } else {
    followType.value = ''
  }
}

/**
 * 重置数据
 */
const resetInfo = () => {
  nextTime.value = ''
  // 输入法
  content.value = ''
  // 图片信息
  imgFiles.value = []
  // 图片信息
  files.value = []
  // 关联商机信息
  business.value = []
  // 关联联系人信息
  selectContactsId.value = contactsId.value || ''
  // 展示关联弹窗
  showRelativeType.value = ''
  batchId.value = ''
  getDefalutFollowType()
}

/**
 * 常用语选择
 */
const commonWordsSelect = (data) => {
  if (content.value) {
    this.$confirm('您选中的常用语将覆盖当前填写内容?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
      customClass: 'is-particulars'
    })
        .then(() => {
          content.value = data
        })
        .catch(() => {
        })
  } else {
    content.value = data
  }
}

/**
 * 快捷添加按钮
 */
const checkRelativeInfos = (data) => {
  if (showRelativeType.value == 'business') {
    business.value = data.data
  }
}
const barClick = (type) => {
  showRelativeType.value = type
  if (type == 'business') {
    showBusinessPopover.value = true
  } else if (type == 'file') {
    cxt.refs.fileInput.click()
  } else if (type == 'img') {
    cxt.refs.imgInput.click()
  }
}

/**
 * 图片选择出发
 */
const uploadFile = (event) => {
  var files = event.target.files
  if (files.length) {
    for (let index = 0; index < files.length; index++) {
      const file = files[index]
      if (
          file.type.indexOf('image') == -1 &&
          showRelativeType.value == 'img'
      ) {
        // $message.error('请上传正确的文件类型')
        ElMessage.error({message: '请上传正确的文件类型'})
        return
      }
    }

    var type = event.target.accept == 'image/*' ? 'img' : 'file'
    for (let index = 0; index < files.length; index++) {
      const file = files[index]
      uploadFileRequest(file, type)
    }
    event.target.value = ''
  }
}

/**
 * 文件上传
 */
const uploadFileRequest = (file, type, result) => {
  $wkUploadFile.upload({
    file: file,
    params: {
      type: type,
      batchId: batchId.value
    }
  }).then(({res}) => {
    const data = res.data || {}
    data.size = fileSize(file.size)
    if (type == 'img') {
      imgFiles.value.push(data)
    } else {
      data['icon'] = getFileTypeIcon(file)
      files.value.push(data)
    }
    if (result) {
      result()
    }
  }).catch(() => {
  })
}

/**
 * 图片附件删除
 */
const deleteImage = (item, index) => {
  deleteImgOrFile('image', item, index)
}

const deleteFile = (item, index) => {
  deleteImgOrFile('file', item, index)
}

const deleteImgOrFile = (type, item, index) => {
  // this.$confirm('确定删除?', '提示', {
  //   confirmButtonText: '确定',
  //   cancelButtonText: '取消',
  //   type: 'warning'
  // })
  ElMessageBox.confirm('确定删除?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    crmFileDeleteAPI({
      id: item.fileId
    }).then(res => {
      if (type == 'image') {
        imgFiles.value.splice(index, 1)
      } else {
        files.value.splice(index, 1)
      }
      ElMessage.success({message: '操作成功'})
    }).catch(() => {
    })
  }).catch(() => {
  })
}

/**
 * 删除全部 type 1 是附件 2 是图片
 */
const deleteAllFile = (type) => {
  if (batchId.value) {
    ElMessageBox.confirm('确定删除?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      crmFileRemoveByBatchIdAPI({
        batchId: batchId.value,
        type
      })
          .then(res => {
            if (type == 2) {
              imgFiles.value = []
            } else {
              files.value = []
            }
            ElMessage.success({message: '操作成功'})
          })
          .catch(() => {
          })
    })
        .catch(() => {
        })
  }
}

/**
 * 删除相关
 */
const deleteRelate = (data, index) => {
  business.value.splice(index, 1)
}

const inputFocus = () => {
  nextTick(() => {
    cxt.refs.textarea.focus()
    emits('focus')
  })
}

/**
 * 发布
 */
const handleConfirm = () => {
  if (!content.value) {
    ElMessage.error({message: '请输入跟进内容'})
    return
  }

  const params = {}
  params.activityId = data.value.activityId
  params.activityType = data.value.activityType
  params.activityTypeId = id.value
  params.content = content.value
  params.category = followType.value
  const businessIds = business.value.map(element => {
    return element.businessId || element.id
  })

  params.batchId = batchId.value
  params.businessIds = businessIds.join(',')
  params.contactsIds = selectContactsId.value

  params.nextTime = nextTime.value || ''
  params.isEvent = 0
  loading.value = true
  crmActivityUpdateAPI(params)
      .then(res => {
        this.loading = false
        ELMessage.success({message: '编辑成功'})
        emits('save', res.data)
        handleCancel()
      }).catch(() => {
    loading.value = false
  })
}

/**
 * 取消选择
 */
const handleCancel = () => {
  emits('update:visible', false)
}


</script>

<style lang="scss" scoped>
.mix-content {
  position: relative;
  border: 1px solid #e6e6e6;
  border-radius: 3px;
  background-color: white;
  padding: 8px 8px 0;
  margin: 10px 15px 20px;

  &__body {
    height: 40vh;
    overflow-y: auto;
  }

  &-select {
    .el-select {
      width: 110px;
      margin-right: 8px;
    }

    .el-date-editor {
      width: 200px;
      margin-right: 8px;
    }
  }

  .i-cont {
    padding: 8px 0px;

    .wk-write {
      color: #e6e6e6;
      font-size: 15px;
    }
  }
}


.i-cont :deep( .el-textarea__inner) {
  border: none;
  padding: 0;
}

/** 底部bar  */
.bar-cont {
  .handle-button {
    color: #666;
    font-size: 12px;

    :deep( i ) {
      font-size: 12px;
      margin-right: 5px;
    }
  }

  .handle-button:hover {
    color: #2362FB;
  }
}

.file-input {
  display: none;
}

.send-btn {
  float: right;
  font-size: 12px;
  padding: 5px 9px;
  margin-top: -5px;
}
</style>
